package com.leetcode.partition5;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/8/16 10:31
 */
public class LC429N叉树的层序遍历 {

    public static List<List<Integer>> levelOrder(Node root) {
        return bfs(root);
    }

    private static List<List<Integer>> bfs(Node root) {
        List<List<Integer>> answer = new ArrayList<>();
        if (root == null) return answer;
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> levelList = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                Node cur = queue.pollFirst();
                levelList.add(cur.val);
                if (cur.children != null && cur.children.size() > 0) {
                    queue.addAll(cur.children);
                }
            }
            answer.add(levelList);
        }
        return answer;
    }

    private static class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }
}
